<?php

namespace common\service;

use common\model\SaasModuleModel;
use support\SingletonTrait;

class SaasModuleService
{
    use SingletonTrait;


    protected $moduleData = [];

    protected $moduleByCode = [];

    protected $moduleById = [];

    /**
     * @param string $code
     * @return mixed|null
     */
    public function byCode(string $code)
    {
        $this->getModuleData();
        return $this->moduleByCode[$code] ?? null;
    }

    /**
     * @param int $id
     * @return mixed|null
     */
    public function byId(int $id)
    {
        $this->getModuleData();
        return $this->moduleById[$id] ?? null;
    }

    private function getModuleData()
    {
        if (empty($this->moduleData)) {
            $this->moduleData = model(SaasModuleModel::class)->select();
            foreach ($this->moduleData as $moduleIndex => $moduleDatum) {
                $this->moduleById[$moduleDatum['id']] = &$this->moduleData[$moduleIndex];
                $this->moduleByCode[$moduleDatum['code']] = &$this->moduleData[$moduleIndex];
            }

            // todo 写一个定时器 定时更新这个data
        }
    }
}
